import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { User } from './user.schema';
import { InjectModel } from '@nestjs/mongoose';
import { UserEntity } from './user.entity';

@Injectable()
export class UserService {
  private readonly users: UserEntity[];
  constructor(@InjectModel('User') private userModel: Model<User>) {
    this.users = [
      {
        id: 1,
        username: 'admin',
        password: 'chatly0510',
      },
    ];
  }
  async login({ username, password }) {
    const user = await this.find(username);
    if (user && password === user.password) {
      return 'chatlytoken12KFif9807KDJF89kdf8lsd89';
    } else {
      return null;
    }
  }
  /**
   * find user by username
   * @param username
   */
  async find(username: string): Promise<UserEntity> {
    const user = this.users.find((user) => user.username === username);
    if (user) return user;
    else return null;
  }
  async getUser({
    phone = '',
    page = 1,
    pageSize: limit = 10,
    startDate = '0',
    endDate = new Date().toLocaleString(),
  }) {
    const regex = new RegExp(phone, 'i');
    const skip = (page - 1) * limit;
    const total = await this.userModel.countDocuments({
      phone: { $regex: regex },
      created_time: {
        $gte: typeof startDate === 'string' ? new Date(startDate) : startDate,
        $lte: typeof endDate === 'string' ? new Date(endDate) : endDate,
      },
    });
    const users = await this.userModel
      .find({
        phone: { $regex: regex },
        created_time: {
          $gte: typeof startDate === 'string' ? new Date(startDate) : startDate,
          $lte: typeof endDate === 'string' ? new Date(endDate) : endDate,
        },
      })
      .select('phone u_name sex age created_time updated_time')
      .sort({ created_time: -1 })
      .skip(skip)
      .limit(limit);
    return {
      page,
      limit,
      total,
      pageCount: Math.ceil(total / limit),
      list: users,
    };
  }
}
